#ifndef MYSQLPOOL_H
#define MYSQLPOOL_H

#include "precomp.h"

//#include <QSqlDatabase>
//#include <QSqlQuery>
//#include <QHash>
//#include <QQueue>
//#include <QMutex>

class MySqlPool
{
public:
    MySqlPool()
    {
//        for (int i = 0; i < m_maxConnections; ++i) {
//            addConnection();
//        }
    }
    void initDbParam(const QString &host, const int port,const QString &database, const QString &user, const QString &password, int maxConnections)
    {
        m_host=host;
        m_port =port;
        m_database=database;
        m_user=user;
        m_password=password;
        m_maxConnections=maxConnections;
    }
    QSqlDatabase getConnection()
    {
        QMutexLocker locker(&m_mutex);
        while (!m_availableConnections.isEmpty()) {
            QSqlDatabase conn = m_availableConnections.dequeue();
            if (!conn.isOpen())
            {
                conn.close();
                openConnection(conn);
            }
            m_connections[&conn] = true; // 标记为正在使用
            return conn;
        }

        // 如果所有连接都在使用，且不超过最大连接数，则创建新的连接
        if (m_connections.size() < m_maxConnections) {
            QSqlDatabase conn = addConnection();
            openConnection(conn);
            m_connections[&conn] = true; // 新建连接并标记为正在使用
            return conn;
        }

        // 如果超出最大连接数，则返回空数据库对象
        return QSqlDatabase();
    }

    void releaseConnection(QSqlDatabase &connection)
    {
        QMutexLocker locker(&m_mutex);
        connection.transaction(); // 可能需要清理事务状态
        connection.rollback(); // 回滚可能存在的事务，确保连接可重用
        m_connections[&connection] = false;
        m_availableConnections.enqueue(connection);
    }

private:
    bool checkConnection(QSqlDatabase &conn)
    {
        // 这里只是一个示例，实际中可能需要执行一个查询语句来验证连接有效性
        return true; // 假设连接总有效，实际情况需要具体实现
    }

    QSqlDatabase addConnection()
    {
        QSqlDatabase conn = QSqlDatabase::addDatabase("QMYSQL", QStringLiteral("pool_connection_%1").arg(m_connections.size()));
        conn.setHostName(m_host);
        conn.setDatabaseName(m_database);
        conn.setUserName(m_user);
        conn.setPassword(m_password);
        m_connections[&conn] = false;
        return conn;
    }

    void openConnection(QSqlDatabase &conn)
    {
        if (!conn.open()) {
            throw std::runtime_error("Failed to open database connection.");
        }
    }

    QString m_host;
    QString m_database;
    QString m_user;
    QString m_password;
    int m_port;
    int m_maxConnections;
    QQueue<QSqlDatabase> m_availableConnections;
    QHash<QSqlDatabase *, bool> m_connections; // 用于跟踪哪些连接正在使用
    QMutex m_mutex;
};



#endif // MYSQLPOOL_H
